import { ApiCall } from "tsrpc";
import {
  ReqGetEInfo,
  ResGetEInfo,
  info,
  safeStu
} from "../../shared/protocols/Get/PtlGetEInfo";
import { Global } from "../../Global/index";

export default async function (call: ApiCall<ReqGetEInfo, ResGetEInfo>) {
  // TODO
  const { course, requiredExp } = call.req;

  const p1 = Global.collection("selectCourses")
    .aggregate([
      {
        $match: {
          course,
        },
      },
      {
        $lookup: {
          from: "users",
          localField: "student",
          foreignField: "_id",
          as: "student",
        },
      },
      {
        $unwind: "$student",
      },
      { $replaceRoot: { newRoot: "$student" } },
      {
        $project:{
            'email':false,
            'password':false,
            'role':false,
            'school':false,
            'gender':false,
            'portrait':false,
        }
      }
    ])
    .toArray();

  const p2 = Global.collection("experiments")
    .aggregate([
      {
        $match: {
          course,
          _id: {
            $in: requiredExp,
          },
        },
      },
      {
        $lookup: {
          from: "userExperiments",
          localField: "_id",
          foreignField: "experiment",
          as: "userExperiments",
        },
      },
      {
        $lookup: {
          from: "users",
          localField: "userExperiments.student",
          foreignField: "_id",
          as: "student",
        },
      },
      {
        $project: {
          course: false,
          startTime: false,
          endTime: false,
          questions: false,
          status: false,
          _id: false,
          language:false,

          "student.email": false,
          "student.password": false,
          "student.gender": false,
          "student.portrait": false,
          "student.role": false,
          "student.school": false,
          // 'student._id':false,

          "userExperiments.answers": false,
          "userExperiments.submitTime": false,
          "userExperiments.experiment": false,
          "userExperiments._id": false,
        },
      },
    ])
    .toArray();

  const ret = await Promise.all([p1, p2]);
//   console.log(ret);
  call.succ({
    info:ret[1] as info[],
    students:ret[0] as  safeStu[]
  });
}
